﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using Newtonsoft.Json;
using System.Device.Location;
using System.Text;
using System.Windows.Controls.Primitives;
using Coding4Fun.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Text.RegularExpressions;
using Microsoft.Phone.Tasks;
namespace YiDingCanWp7
{
    public partial class MainPage : PhoneApplicationPage
    {
        int pageindex = 1;
        int pagesize = 20;
        bool haveMore = true;
        int total = 0;
        List<ShopDTO> shoplist = new List<ShopDTO>();
        List<ShopDTO> latestshopdtos = new List<ShopDTO>();
        List<ShopDTO> favorateshops = new List<ShopDTO>();
        string url = BaseConfig.BaseUrl+"/Shop/ShopsForMobile?lat={0}&lng={1}&distance={2}&pageIndex={3}&pageSize={4}&title={5}&shopcatids={6}";
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            performanceProgressBar.IsIndeterminate = false;
            // 将 listbox 控件的数据上下文设置为示例数据
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
           // performanceProgressBar.IsIndeterminate = false;
            if (BaseConfig.IsLogined)
            {
                LoginImage.Visibility = Visibility.Collapsed;
            }
            else
            {
                LoginImage.Visibility = Visibility.Visible;
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            LatestShopsSettings set = new LatestShopsSettings();
            LatestShop.ItemsSource = set.LatestShops;
            FavoriteShops favs = new FavoriteShops();
            FavShopList.ItemsSource = favs.FavorateShop;
            if (BaseConfig.IsLogined)
            {
                LoginImage.Visibility = Visibility.Collapsed;
                imageUserCenter.Visibility = Visibility.Visible;
            }
            else
            {
                LoginImage.Visibility = Visibility.Visible;
                imageUserCenter.Visibility = Visibility.Collapsed;
            }
            base.OnNavigatedTo(e);
        }
        // 为 ViewModel 项加载数据
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            
          
           // Btn_NextPage.Visibility = Visibility.Collapsed;
            //List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(ShopList);
            //foreach (ScrollBar scrollBar in scrollBarList)
            //{
            //    if (scrollBar.Orientation == System.Windows.Controls.Orientation.Horizontal)
            //    {

            //    }
            //    else
            //    {
            //        scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(verticalScrollBar_ValueChanged);
            //    }
            //}
            
        }
        public static double[] GetLocationProperty()
        {
            double[] latLong = new double[2];
            GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
            watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
            GeoCoordinate coord = watcher.Position.Location;
            if (coord.IsUnknown != true)
            {
                latLong[0] = 39.9770162093267;
                    //coord.Latitude;
                latLong[1] = 116.343085267181;
                    //coord.Longitude;
            }
            return latLong;
        }
       
        public bool IsLoaded = false;
        
        private void Search_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SearchSetting.xaml", UriKind.RelativeOrAbsolute));
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddShop.xaml", UriKind.RelativeOrAbsolute));
        }
        private void Btn_NextPage_Click(object sender, RoutedEventArgs e)
        {
            //GetShops();
        }
        Popup popup = new Popup() { IsOpen = false };
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            LatestShopsSettings.Remove(contextMenuDataItem);
            latestshopdtos=LatestShopsSettings.Instance.LatestShops;
            latestshopdtos.Remove(contextMenuDataItem);
            LatestShop.ItemsSource = latestshopdtos;
            
            ToastPrompt toast = new ToastPrompt(); //实例化 

            toast.Title = "删除成功"; //设置标题 
            toast.Message = "删除成功"; //设置正文消息 
            toast.FontSize = 50; //设置文本大小(可选) 
            toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向 
            toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 
            toast.Background = new SolidColorBrush(Colors.LightGray); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.Red); //前景色(可选)


            toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
            toast.Show(); 
        }
        private void MenuItemPhone_Click(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            //MessageBox.Show(contextMenuDataItem.Phone);
            appbar_MakeACall_Click(contextMenuDataItem);

        }
        private void appbar_MakeACall_Click(ShopDTO shop)
        {
            Regex regex = new Regex(@"((\d{11})|((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})))", RegexOptions.IgnorePatternWhitespace);
            if (string.IsNullOrEmpty(shop.Phone))
            {
                MessageBox.Show("号码不存在!");
                return;
            }
            MatchCollection mc = regex.Matches(shop.Phone);
            if (mc.Count > 1)
            {
                popup.Height = 300;
                popup.Width = 400;
                popup.VerticalOffset = 100;
                PopupControl control = new PopupControl();
                foreach (Match item in mc)
                {
                    Button ctrl = new Button();
                    ctrl.Content = item.Value;
                    ctrl.Tag = shop;
                    ctrl.Click += new RoutedEventHandler(ctrl_Click);
                    control.LayoutRoot.Children.Add(ctrl);
                }
                popup.Child = control;
                popup.IsOpen = true;
            }
            else if (mc.Count > 0)
            {
                LatestShopsSettings.Add(shop);
                PhoneCallTask p = new PhoneCallTask();
                p.PhoneNumber = mc[0].Value;
                p.Show();
                
            }
        }

        void ctrl_Click(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as Button).Tag;
            LatestShopsSettings.Add(contextMenuDataItem);
            PhoneCallTask p = new PhoneCallTask();
            p.PhoneNumber = ((Button)sender).Content.ToString();
            p.Show();
            popup.IsOpen = false;
        }
        static T FindChildOfType<T>(DependencyObject root) where T : class {
            var queue = new Queue<DependencyObject>();
            queue.Enqueue(root);
            while (queue.Count>0)
            {
                DependencyObject current = queue.Dequeue();
                for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (typedChild!=null)
                    {
                        return typedChild;
                    }
                    queue.Enqueue(child);
                }
            }
            return null;
        }
        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {
            ScrollBar scrollBar = (ScrollBar)sender;
            object valueObj = scrollBar.GetValue(ScrollBar.ValueProperty);
            object maxObj = scrollBar.GetValue(ScrollBar.MaximumProperty);
            if (valueObj != null && maxObj != null)
            {
                double value = (double)valueObj;
                double max = (double)maxObj - 1.0;
                if (value >= max)
                {
                    //读取下一页的数据
                    //GetShops();
                }
            }
        }
        public static List<T> GetVisualChildCollection<T>(object parent) where T : UIElement
        {
            List<T> visualCollection = new List<T>();
            GetVisualChildCollection(parent as DependencyObject, visualCollection);
            return visualCollection;
        }
        private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : UIElement
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child is T)
                {
                    visualCollection.Add(child as T);
                }
                else if (child != null)
                {
                    GetVisualChildCollection(child, visualCollection);
                }
            }
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            FavoriteShops.Remove(contextMenuDataItem);
            favorateshops= FavoriteShops.Instance.FavorateShop;
            favorateshops.Remove(contextMenuDataItem);
            FavShopList.ItemsSource = favorateshops;
            ToastPrompt toast = new ToastPrompt(); //实例化 

            toast.Title = "删除成功"; //设置标题 
            toast.Message = "删除成功"; //设置正文消息 
            toast.FontSize = 50; //设置文本大小(可选) 
            toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向 
            toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 
            toast.Background = new SolidColorBrush(Colors.LightGray); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.Red); //前景色(可选)


            toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
            toast.Show(); 
        }
        void toast_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            //add some code here
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            FavoriteShops.AddFavorate(contextMenuDataItem);
            favorateshops=FavoriteShops.Instance.FavorateShop;
            FavShopList.ItemsSource = favorateshops;
           
            ToastPrompt toast = new ToastPrompt(); //实例化 

            toast.Title = "收藏成功"; //设置标题 
            toast.Message = "收藏成功"; //设置正文消息 
            toast.FontSize = 50; //设置文本大小(可选) 
            toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向 
            toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 
            toast.Background = new SolidColorBrush(Colors.LightGray); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.Red); //前景色(可选)


            toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
            toast.Show(); 
        }
        private void panarama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //MessageBox.Show(panarama.SelectedIndex.ToString());
            if (panarama.SelectedIndex == 1)
                {
                    if (!IsLoaded)
                    {
                        //GetShops();
                    }
                }
                if (panarama.SelectedIndex == 2)
                {

                }
                if (panarama.SelectedIndex == 3)
                {

                }
        }
        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        
        {
           // panarama.SelectedItem = localpanaramaitem;
           // panarama.DefaultItem = NavPanoramaItem;
           // panarama.SetValue(Panorama.SelectedItemProperty, panarama.Items[2]);
            NavigationService.Navigate(new Uri("/ShopList.xaml?type=local", UriKind.RelativeOrAbsolute));
        }
        private void Image_MouseLeftButtonUp_Login(object sender, MouseButtonEventArgs e)
        {
            if (BaseConfig.IsLogined)
            {
                
            NavigationService.Navigate(new Uri("/PersonnelPage.xaml?type=latest", UriKind.RelativeOrAbsolute));
            }
            else
            {
                NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }
        private void Image_MouseLeftButtonUp_Setting(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml?type=favorite", UriKind.RelativeOrAbsolute));
        }
        private void Image_MouseLeftButtonUp_Share(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ShopList.xaml?type=share", UriKind.RelativeOrAbsolute));
        }
        private void MenuItemGoToShop_Click(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            NavigationService.Navigate(new Uri("/ShopDetailPivot.xaml?shopid=" +contextMenuDataItem.ShopId, UriKind.RelativeOrAbsolute));
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void Setting_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void Image_MouseLeftButtonUp_Search(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SearchSetting.xaml", UriKind.RelativeOrAbsolute));
        }

        private void Image_MouseLeftButtonUp_Feedback(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/AppFeedback.xaml", UriKind.RelativeOrAbsolute));
        }


    }
}